import {
	getList,
	deleteCustomerDemand,
	editCustomerDemand,
	batchAddCustomerDemand
} from "../apis/customerDemandAPI";
import { ElMessage } from "element-plus";
import { ref, reactive, onUnmounted } from "vue";
export const useCustomerDemand = () => {
	/**
	 * 加载状态
	 */
	const loading = ref(false);
	// 定时收集状态
	const isCollecting = ref(false);
	// 定时器引用
	let collectTimer = null;

	const searchForm = reactive({
		demandCode: null,
		demandType: null,
		title: null,
		urgencyLevel: null,
		demandStatus: null,
	});

	// 搜索
	const handleSearch = () => {
		pagination.currentPage = 1;
		LoadingCustomerDemandList();
	};

	// 重置搜索
	const handleReset = () => {
		Object.assign(searchForm, {
			demandCode: null,
			demandType: null,
			title: null,
			urgencyLevel: null,
			demandStatus: null,
		});
		pagination.currentPage = 1;
		LoadingCustomerDemandList();
	};

	// 分页信息
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0,
	});

	// 分页大小改变
	const handleSizeChange = (size) => {
		pagination.pageSize = size;
		LoadingCustomerDemandList();
	};

	// 页码改变
	const handleCurrentChange = (current) => {
		pagination.currentPage = current;
		LoadingCustomerDemandList();
	};



	// 客户列表
	const customerDemandList = ref([]);

	const LoadingCustomerDemandList = async () => {
		loading.value = true;

		try {
			const params = {
				...searchForm,
				page: pagination.currentPage,
				pageSize: pagination.pageSize,
			};
			const { code, data, message } = await getList(params);
			if (code === 200) {
				customerDemandList.value = data.records;
				pagination.total = data.total;
			} else {
				ElMessage.error(message);
			}
		} catch (error) {
			console.error("加载客户列表失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 查看对话框
	const viewDialogVisible = ref(false);
	const viewForm = ref({});
	const handleView = (row) => {
		viewForm.value = row;
		viewDialogVisible.value = true;
	};

	// 删除功能
	const handleDelete = async (id) => {
		loading.value = true;
		try {
			const response = await deleteCustomerDemand(id);
			if (response.code === 200) {
				ElMessage.success("删除成功");
				LoadingCustomerDemandList();
			} else {
				ElMessage.error(response.message || "删除失败");
			}
		} catch (error) {
			console.error("删除客户失败:", error);
			ElMessage.error("删除失败，请稍后重试");
		} finally {
			loading.value = false;
		}
	};

	// 编辑功能
	const editDialogVisible = ref(false);

	// 编辑表单数据
	const editForm = reactive({
		demandCode: null,
		customerId: null,
		customerName: null,
		powerZoneId: null,
		powerZoneName: null,
		equipmentId: null,
		equipmentName: null,
		demandType: null,
		title: null,
		description: null,
		requiredPower: null,
		urgencyLevel: null,
		demandStatus: null,
		processingMethod: null,
	});
	const editLoading = ref(false);

	const handleResponse = (row) => {
		// 重置表单
		Object.keys(editForm).forEach(key => {
			editForm[key] = null;
		});
		// 复制所有字段，包括可能存在的名称字段
		Object.assign(editForm, row);
		// 如果数据中没有名称字段，使用ID作为默认显示
		editForm.customerName = editForm.customerName || `客户${editForm.customerId}`;
		editForm.powerZoneName = editForm.powerZoneName || `区域${editForm.powerZoneId}`;
		editForm.equipmentName = editForm.equipmentName || `设备${editForm.equipmentId}`;
		editDialogVisible.value = true;
	};

	const saveResponse = async () => {
		editLoading.value = true;
		try {
			await editCustomerDemand(editForm);
			ElMessage.success("响应成功");
			editDialogVisible.value = false;
			LoadingCustomerDemandList();
		} catch (error) {
			console.error("响应客户需求失败:", error);
			ElMessage.error("响应失败，请稍后重试");
		} finally {
			editLoading.value = false;
		}
	};

	// 需求类型选项
	const demandTypeOptions = [
		{ label: "新装增容", value: 0 },
		{ label: "故障报修", value: 1 },
		{ label: "用电咨询", value: 2 },
	];

	// 生成随机字符串
	const generateRandomString = (length = 8) => {
		const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		let result = '';
		for (let i = 0; i < length; i++) {
			result += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return result;
	};

	// 生成随机数据
	const generateRandomData = () => {
		const titles = ['电力设备故障', '新增用电需求', '电费缴纳咨询', '电表异常', '线路老化更换', '用电量突增查询'];
		const descriptions = ['设备运行异常，需要及时检修', '业务扩展需要增加用电容量', '电费计算有疑问需要咨询', '电表显示异常，读数不准确', '线路老化存在安全隐患', '近期用电量突增，需要排查原因'];

		const demandType = Math.floor(Math.random() * 3);
		const titleIndex = Math.floor(Math.random() * titles.length);
		const descriptionIndex = Math.floor(Math.random() * descriptions.length);
		const urgencyLevel = Math.floor(Math.random() * 3); // 0:一般, 1:紧急, 2:特急

		return {
			demandCode: `DEM-${Date.now()}-${generateRandomString(6)}`,
			demandType: demandType,
			title: titles[titleIndex],
			description: descriptions[descriptionIndex],
			requiredPower: demandType === 0 ? Math.random() * 50 + 10 : null,
			urgencyLevel: urgencyLevel,
			demandStatus: 0
		};
	};

	// 开始定时收集需求
	const startCollecting = () => {
		if (isCollecting.value) return;

		isCollecting.value = true;
		ElMessage.success('开始定时收集需求数据');

		// 每隔5秒收集一次
		collectTimer = setInterval(async () => {
			try {
				// 生成3-5条数据
				const dataCount = Math.floor(Math.random() * 3) + 3;
				const dataList = [];

				for (let i = 0; i < dataCount; i++) {
					const randomData = generateRandomData();
					dataList.push(randomData);
				}

				// 使用批量添加API
				const response = await batchAddCustomerDemand(dataList);
				if (response.code === 200) {
					console.log(`成功批量收集 ${dataCount} 条需求数据`);
					ElMessage.success(`成功采集 ${dataCount} 条需求数据`);
					// 重新加载列表以显示新数据
					LoadingCustomerDemandList();
				} else {
					console.error('批量添加失败:', response.message);
					ElMessage.error(`采集失败: ${response.message}`);
				}
			} catch (error) {
				console.error('定时收集数据失败:', error);
				ElMessage.error('采集数据时发生错误');
			}
		}, 5000);
	};

	// 停止采集需求
	const stopCollecting = () => {
		if (!isCollecting.value) return;

		isCollecting.value = false;
		clearInterval(collectTimer);
		collectTimer = null;
		ElMessage.success('停止采集需求数据');
	};

	// 组件卸载时清除定时器
	onUnmounted(() => {
		if (collectTimer) {
			clearInterval(collectTimer);
		}
	});

	// 格式化客户类型
	const formatType = (type) => {
		const typeMap = {
			0: "新装增容",
			1: "故障报修",
			2: "用电咨询",
		};
		return typeMap[type] || "未知";
	};
	// 格式化客户状态
	const formatStatus = (status) => {
		const statusMap = {
			0: "待处理",
			1: "已完成",
		};
		return statusMap[status] || "未知";
	};
	// 格式化紧急程度
	const formatUrgency = (level) => {
		const urgencyMap = {
			0: "一般",
			1: "紧急",
			2: "特急"
		};
		return urgencyMap[level] || "未知";
	};

	// 紧急程度选项
	const urgencyOptions = [
		{ label: '一般', value: 0 },
		{ label: '紧急', value: 1 },
		{ label: '特急', value: 2 }
	];

	// 需求状态选项
	const demandStatusOptions = [
		{ label: '待处理', value: 0 },
		{ label: '已完成', value: 1 }
	];

	return {
		loading,
		// 客户列表
		customerDemandList,
		LoadingCustomerDemandList,
		// 查看客户详情
		viewDialogVisible,
		viewForm,
		handleView,
		// 删除客户
		handleDelete,
		// 编辑客户
		editDialogVisible,
		editForm,
		saveResponse,
		handleResponse,
		demandTypeOptions,
		editLoading,
		// 搜索表单
		searchForm,
		// 搜索
		handleSearch,
		// 重置搜索
		handleReset,

		// 分页信息
		pagination,
		// 分页切换
		handleCurrentChange,
		handleSizeChange,

		// 选项数据
		urgencyOptions,
		demandStatusOptions,
		// 格式化方法
		formatType,
		formatStatus,
		formatUrgency,
		// 定时收集功能
		isCollecting,
		startCollecting,
		stopCollecting
	};
};
